package top.letscode.study.apollo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author: zhengzhq
 * @Date: 2019-09-02 13:46
 * @Description: 文件工具类
 */
public class FileUtil {

    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 将文件写到classpath
     *
     * @param fileName 文件名
     * @param content  文件内容
     * @return
     */
    public static File writeToClassPath(String fileName, String content) {
        String folder = FileUtil.class.getClassLoader().getResource("").getPath();

        return write(folder, fileName, content);
    }

    /**
     * 将制定内容写到本地磁盘
     *
     * @param folder   文件目录
     * @param fileName 文件名
     * @param content  文件内容
     */
    public static File write(String folder, String fileName, String content) {
        File file = new File(folder + File.separator + fileName);

        try (FileWriter writer = new FileWriter(file)) {
            writer.write(content);
        } catch (IOException e) {
            logger.error("write file {} error", file.getAbsolutePath(), e);

            throw new RuntimeException("write file error", e);
        }

        return file;
    }
}
